package com.bolins.examples.subspringside.mongodb;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * MongoDB 数据库实例
 * 
 * @author liuys
 * 
 *         see TestCRUDWithMongoDB
 */
public class MongoDBConfig {
	public static final String DEFAULT_HOST = "127.0.0.1";
	public static final int DEFAUTL_PORT = 27017;

	private static Mongo mongo = null;

	private MongoDBConfig() {
	}

	private static void initMongo(String host, int port) {
		try {
			mongo = new Mongo(host, port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}

	public static Mongo getInstance() {
		if (mongo == null) {
			initMongo(DEFAULT_HOST, DEFAUTL_PORT);
		}

		return mongo;
	}

	public static Mongo getInstance(String host) {
		if (mongo == null) {
			initMongo(host, DEFAUTL_PORT);
		}

		return mongo;
	}

	public static Mongo getInstance(String host, int port) {
		if (mongo == null) {
			initMongo(host, port);
		}

		return mongo;
	}

	public static List<String> getDBNames() {
		if (mongo == null) {
			initMongo(DEFAULT_HOST, DEFAUTL_PORT);
		}
		return mongo.getDatabaseNames();
	}

	public static DB getDB(String dbName) {
		if (mongo == null) {
			initMongo(DEFAULT_HOST, DEFAUTL_PORT);
		}

		return mongo.getDB(dbName);
	}

	public static void dropDB(String dbName) {
		if (mongo == null) {
			initMongo(DEFAULT_HOST, DEFAUTL_PORT);
		}

		mongo.dropDatabase(dbName);
	}

}
